﻿#-------------------------------------------------------------------------------
# Name:        utils
# Purpose:     A set of common classes and functions used in the program
#
# Author:      GaiveR
#
# Created:     25.08.2011
# Copyright:   (c) ASM-Team 2011
# Licence:     Private
#-------------------------------------------------------------------------------
#!/usr/bin/env python


import uuid
import pygame
from consts import *

################################################################################


# нагло спизжен из battle city
class Timer(object):
    def __init__(self):
        self.timers = []

    def add(self, interval, f, repeat=-1):
        options = {
            "interval": interval,
            "callback": f,
            "repeat"  : repeat,
            "times"	  : 0,
            "time"	  : 0,
            "uuid"	  : uuid.uuid4()
        }
        self.timers.append(options)

        return options["uuid"]

    def destroy(self, uuid_nr):
        for timer in self.timers:
            if timer["uuid"] == uuid_nr:
                self.timers.remove(timer)
                return

    def update(self, time_passed):
        for timer in self.timers:
            timer["time"] += time_passed
            if timer["time"] > timer["interval"]:
                timer["time"] -= timer["interval"]
                timer["times"] += 1
                if timer["repeat"] > -1 and timer["times"] == timer["repeat"]:
                    self.timers.remove(timer)
                try:
                    timer["callback"]()
                except:
                    try:
                        self.timers.remove(timer)
                    except:
                        pass

################################################################################

def postUserEvent(event_type:int, **adv_info) -> None:
    """
    Создает и отправляет пользовательское событие.
        event_type - константа из модуля consts
        adv_info - набор именованных аргументов с дополнительной информацией
    """

    pygame.event.post(
        pygame.event.Event(OTHER_EVENT, adv_type=event_type, **adv_info)
    )

################################################################################
